package me.yushuai.wukong.base.service.impl;

import io.minio.errors.MinioException;
import me.yushuai.wukong.base.api.dto.PagingSearchAttachment;
import me.yushuai.wukong.base.entity.Attachment;
import me.yushuai.wukong.base.repository.AttachmentRepository;
import me.yushuai.wukong.base.service.AttachmentService;
import me.yushuai.wukong.common.dto.PageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件管理业务类
 *
 * @author zhoushuai@189.cn
 * @since 2023-09-19
 */
@Service
public class AttachmentServiceImpl implements AttachmentService {

    @Autowired
    private AttachmentRepository attachmentRepository;

//    @Autowired
//    private MinioClient minioClient;

    @Override
    public void uploadFile(MultipartFile multipartFile) throws MinioException, IOException, NoSuchAlgorithmException,
            InvalidKeyException {
//        MinioUtils.uploadFile(minioClient, "", multipartFile);
        final Attachment attachment = new Attachment();
        attachment.setOriginalName(multipartFile.getOriginalFilename());
        attachment.setFileType(multipartFile.getContentType());

        this.attachmentRepository.save(attachment);
    }


    @Override
    public PageDTO<Attachment> page(PagingSearchAttachment pagingSearch) {

        //1. 分页条件查询
        final PageRequest pageRequest = PageRequest.of(pagingSearch.getCurrent(), pagingSearch.getSize());
        final Specification<Attachment> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasText(pagingSearch.getFileName())) {
                list.add(criteriaBuilder.equal(root.get("originalName").as(String.class), pagingSearch.getFileName()));
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        //2. 执行查询操作
        Page<Attachment> pageResult = this.attachmentRepository.findAll(spec, pageRequest);


        //3. 对象转换并返回并返回
        pagingSearch.setTotal(pageResult.getTotalElements());
        return PageDTO.of(pagingSearch, pageResult.getContent());
    }

}
